package online.heycm.platform.web.common.exception;

import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

import lombok.extern.slf4j.Slf4j;
import online.heycm.platform.common.entity.exception.BizException;
import online.heycm.platform.common.entity.result.Result;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author heycm
 * @since 2023/12/21 18:57
 */
@Slf4j
@RestControllerAdvice
public class WebExceptionHandler {

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Throwable.class)
    public Result error(Throwable e) {
        log.error("Throwable 发生未知异常！", e);
        return Result.error(500, "服务器错误");
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result error(Exception e) {
        log.error("Exception 发生未知异常！", e);
        return Result.error(500, "服务器错误");
    }

    @ExceptionHandler(BizException.class)
    public Result error(BizException e) {
        return Result.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public Result handleValidatedException(Exception e) {
        String message;
        if (e instanceof MethodArgumentNotValidException) {
            // BeanValidation exception
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            message = getParamError(ex.getBindingResult());
        } else if (e instanceof ConstraintViolationException) {
            // BeanValidation GET simple param
            ConstraintViolationException ex = (ConstraintViolationException) e;
            message = ex.getConstraintViolations().stream()
                    .map(ConstraintViolation::getMessage)
                    .collect(Collectors.joining("; ")
                    );
        } else if (e instanceof BindException) {
            // BeanValidation GET object param
            BindException ex = (BindException) e;
            message = getParamError(ex.getBindingResult());
        } else {
            message = "参数错误";
        }

        return Result.error(400, message);
    }

    private String getParamError(BindingResult br) {
        List<FieldError> fieldErrors = br.getFieldErrors();
        if (CollectionUtils.isEmpty(fieldErrors)) {
            return "参数错误";
        }
        StringJoiner joiner = new StringJoiner(";");
        for (FieldError fieldError : fieldErrors) {
            String field = fieldError.getField();
            String message = fieldError.getDefaultMessage();
            if (message != null && message.contains("java.lang.NumberFormatException")) {
                message = "参数类型异常";
            }
            joiner.add(field + ":" + message);
        }
        return joiner.toString();
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result error(MissingServletRequestParameterException e) {
        return Result.error(400, "缺少参数: " + e.getParameterName());
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result error(HttpRequestMethodNotSupportedException e) {
        return Result.error(400, "不支持的请求方式: " + e.getMessage());
    }
}
